import dayjs from "dayjs";
import CONSTMAP from "@/constant";
import { filterCity } from "@/utils";

/**
 * Show plural label if time is plural number
 * @param {number} time
 * @param {string} label
 * @return {string}
 */
function pluralize(time, label) {
	if (time === 1) {
		return time + label;
	}
	return time + label + "秒";
}

/**
 * @param {number} time
 */
export function timeAgo(time) {
	const between = Date.now() / 1000 - Number(time);
	if (between < 3600) {
		return pluralize(~~(between / 60), " 分钟");
	} else if (between < 86400) {
		return pluralize(~~(between / 3600), " 小时");
	} else {
		return pluralize(~~(between / 86400), " 天");
	}
}

/**
 * 全局常量过滤器
 * @parmas val 过滤器默认传入的值
 * @parmas constObj 常量对应的键值
 * @parmas key 返回常量对应的key
 * */
export function constFilter(val, constObj, key = "label") {
	if (!constObj) return false;
	const newVal = CONSTMAP[constObj]?.find(e => e.value == val);
	return newVal && newVal[key];
}

// 时间格式化
export function dateFormat(val, format = "YYYY-MM-DD") {
	return dayjs(val).format(format);
}

// 保留小数
export function toFixed(val, num = 2) {
	if (!val || val == Infinity) return 0;
	return Number(val)
		.toFixed(num)
		.replace(/(\d)(\.00)/, "$1");
}

// 补0
export function prefixInteger(num = 0, n = 4) {
	if (!num) return "-";
	return (Array(n).join(0) + num).slice(-n);
}

export function privacyPhone(phone) {
	if (!phone) return "-";
	return phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
}
export function privacyWechat(wechat) {
	if (!wechat) return "-";
	if (wechat.length <= 4) return "****";
	return wechat.replace(/(\s{4})\s{4,12}(\s{4})/, "$1****$2");
}
export function filterText(val, list = [], props = {}) {
	let nProps = { value: "value", label: "label", ...props };
	let target = list.find(v => v[nProps.value] == val);
	return target?.[nProps.label];
}
export {
	filterCity
}
export default {
	constFilter,
	dateFormat,
	toFixed,
	prefixInteger,
	privacyPhone,
	privacyWechat,
	filterCity,
	filterText
};
